#include "pwm.h"
//TIM2_CH3  PB10 
void pwm_init(void)
{
	TIM_OCInitTypeDef TIM_OCInitStruct;
	GPIO_InitTypeDef GPIO_InitStruct;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct);
	TIM_OCStructInit(&TIM_OCInitStruct);
	
	// 使能 GPIOB 和 AFIO
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO,ENABLE);
	// 使能 TIM2 时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
	
	
	// 配置 PB10 为复用功能推挽输出
	GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_AF_PP;
	GPIO_InitStruct.GPIO_Pin   = GPIO_Pin_8;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStruct);
	
	// 初始化 TIM2 时基单元
	TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStruct.TIM_CounterMode   = TIM_CounterMode_Up;
	//1000次为一毫秒
	TIM_TimeBaseInitStruct.TIM_Period        = 20000 - 1;      //ARR
	TIM_TimeBaseInitStruct.TIM_Prescaler     = 72 - 1;         //PSC
	TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStruct);
	
	// 初始化 TIM2_CH3 输出比较通道
	TIM_OCInitStruct.TIM_OCMode       = TIM_OCMode_PWM1;
	TIM_OCInitStruct.TIM_OCPolarity   = TIM_OCPolarity_High;
	TIM_OCInitStruct.TIM_OutputState  = TIM_OutputState_Enable;
	TIM_OCInitStruct.TIM_Pulse        = 0;  // CCR比较值，在应用中设置
	TIM_OC3Init(TIM4, &TIM_OCInitStruct);
	
	// 使能 TIM2
	TIM_Cmd(TIM4, ENABLE);
}

void pwm_SetCompare(uint16_t compare)
{
	
	TIM_SetCompare3(TIM4,compare);
}